import Toast from '@vant/weapp/toast/toast';
const https = require('../../../../http/https')
const baseurl = https.https.baseurl
const museum = require('../../../../areaList/brance_2/1museum')
const temple = require('../../../../areaList/brance_2/2temple')
const geology = require('../../../../areaList/brance_2/3geology')
const revolution = require('../../../../areaList/brance_2/4revolution')
const greatwall = require('../../../../areaList/brance_2/5greatwall')
const grotto = require('../../../../areaList/brance_2/6grotto')
const tea = require('../../../../areaList/brance_2/7tea')
const glass = require('../../../../areaList/brance_2/8glass')
const financial = require('../../../../areaList/brance_2/9financial')
const castle = require('../../../../areaList/brance_2/10castle')
const app = getApp()
const areaList = require('../../../../areaList/master/areaList')
const brance_all = require('../../../../areaList/brance_all/brance_all')
const image = require('../../../../areaList/imageRoute/image')
const brance_2 = {
  museum,
  temple,
  geology,
  revolution,
  greatwall,
  grotto,
  tea,
  glass,
  financial,
  castle
}

function changefavorites(url, data) {
  return new Promise((resolve) => {
    wx.request({
      url: url,
      method: 'POST',
      data: data,
      header: {
        'content-type': 'application/x-www-form-urlencoded', // 设置Content-Type
      },
      success(res) {
        console.log(res.data);
        if (res.data.code == 1) {
          console.log("请求成功");
          resolve(res.data.result)
        } else if (res.data.code == 0) {
          console.log("请求失败");
        }
      }
    })
  })
}

//防抖动函数
function debounce(func, wait) {
  let timeout
  return function(...args) {
    if (timeout){
      clearTimeout(timeout);
      console.log(111);
    }
    
    timeout = setTimeout(() => {
      func.apply(this, args);
    }, wait);
  };
}

// pages/findmore/findmore.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    current:0,//当前轮播图id
    currentImage:0,//当前图片
    allImageCount:1,//所有图片总数
    routeType: '',//路径英文名
    mapContext: {},
    areaList: [],
    faviorites_status: [], //0表示没收藏 1表示收藏
    faviorites: '../../images/icon/收藏.png',
    areaList_currentId: 0, //当前路径的下标
    currentId: 0, //路径下当前景点的下标
    linear_gradient: "background: linear-gradient(to top, rgba(0, 0, 0, 0.85) 0%, rgba(0, 0, 0, 0) 70%);",
    mainColor: "",
    currentpoint: {}, //当前路线的点位，路径
    bgi_url: [],
    routeName: '',
    remark: '',
    pointsList: [], //当前路线的视野，信息
    longitude: 0,
    latitude: 0,
    scale: 0,
    markers: [],
    customCalloutMarkerIds: [],
    polyline: [],
    swiperdebounce:null,//防抖动函数
    VideoUrls:[],
    isShowVideo:true
  },

  //返回
  returnBack() {
    wx.navigateBack({
      delta: 2,
      fail() {
        wx.switchTab({
          url: '/pages/index/index'
        })
      }
    })
  },

  //视频播放错误
  VideoBinderror(e) {

  },

  //图片加载错误
  ImageBinderror(event) {
    console.log("ImageBinderror");
    const match = event.detail.errMsg.match(/GET (https?:\/\/[^\s]+)/)
    const errUrl = match[1] //获取该图片url
    console.log(errUrl);

    const newBgi_url = this.data.bgi_url.filter(element => element !== errUrl)
    this.setData({
      bgi_url:newBgi_url,
      allImageCount:newBgi_url.length
    })
  },

  //点击地图
  bindMap(res) {
    console.log(res.detail);
  },

  //图片轮播图切换
  ImageChange(res) {
    const currentid = res.detail.current
    this.setData({
      currentImage:currentid
    })
  },

  //点击展示图片
  showImage() {
    wx.previewImage({
      current: this.data.bgi_url[this.data.currentImage],
      urls: this.data.bgi_url
    })
  },

  //轮播图转换
  swiperChange(res) {
    //设置图片
    //console.log(this.data.pointsList);
    const currentId = res.detail.current
    const bgi_url = []
    const VideoUrls = []
    if(currentId === 0) {//如果是第一个页面
      bgi_url.push(image.image.index[this.data.routeType])
    } else if(currentId !== 0) {//如果是详细景点页面
      //找图片
      for(let i = 0;i<10;i++) {
        let bgiSting = 'http://jzroute.oss-cn-hangzhou.aliyuncs.com/'+this.data.routeType+'/'+this.data.routeType+currentId+'.'+i+'.jpg'
        bgi_url.push(bgiSting)
      }
      //找视频
      for (let i = 10; i < 13; i++) {
        let videourl = 'http://jzroute.oss-cn-hangzhou.aliyuncs.com/'+this.data.routeType+'/'+this.data.routeType+currentId+'.'+i+'.mp4'
        VideoUrls.push(videourl)
      }
    }
    
    this.setData({
      bgi_url: bgi_url,
      allImageCount:bgi_url.length,
      currentImage:0,
      currentId: currentId,
      VideoUrls:VideoUrls,
      isShowVideo:true
    })

    //设置文字
    if (currentId === 0) {
      this.setData({
        linear_gradient: "background: linear-gradient(to top, rgba(0, 0, 0, 0.85) 0%, rgba(0, 0, 0, 0) 70%);",
        routeName: this.data.pointsList[currentId].name,
        remark: this.data.pointsList[currentId].remark
      })
    } else {
      this.setData({
        linear_gradient: "background: linear-gradient(to top, rgba(0, 0, 0, 0.1) 0%, rgba(0, 0, 0, 0) 70%);",
        routeName: "",
        remark: ""
      })
    }
    
    const that = this
    this.data.swiperdebounce(that,currentId)

    //设置收藏
    this.setData({
      faviorites: this.data.faviorites_status[currentId] ? '../../images/icon/已收藏.png' : '../../images/icon/收藏.png'
    })
  },

  //导航
  openMapApp() {
    console.log(this.data.currentpoint);
    console.log(this.data.currentId - 1);
    console.log(this.data.currentpoint.markers[0]);
    const latitude = this.data.currentpoint.markers[this.data.currentId - 1].latitude
    const longitude = this.data.currentpoint.markers[this.data.currentId - 1].longitude
    const destination = this.data.pointsList[this.data.currentId].name
    // console.log(latitude,longitude,destination);

    // 调用 openMapApp 方法，参数根据需要填写
    this.data.mapContext.openMapApp({
      latitude: latitude, // 目标纬度
      longitude: longitude, // 目标经度
      destination: destination, // 目的地名称，部分地图App可能需要 // 导航目的地
      success: function (res) {
        console.log(res);
      },
      fail: function (error) {
        console.log(error);
      },
      complete: function (res) {
        console.log(res);
      }
    });
  },

  //收藏
  faviorites() {
    if (!this.data.faviorites_status[this.data.currentId]) {
      //未收藏
      if (app.globalData.number != 0) {
        const url = baseurl + "/route/user/addfavorites"
        const data = {
          number: app.globalData.number,
          name: this.data.pointsList[this.data.currentId].name,
          remark: this.data.pointsList[this.data.currentId].remark,
          areaListCurrentId: this.data.areaList_currentId,
          currentId: this.data.currentId
        }
        changefavorites(url, data).then(res => {
          if (res != null) {
            Toast.success('收藏成功')
            console.log(res);
            let faviorites_route = []
            let faviorites_sights = []
            let count = 0
            res.map(item => {
              const object = {
                id: count,
                img: areaList.areaList[item.areaListCurrentId].pointsList[item.currentId].bgi_url[0],
                name: item.name,
                remark: item.remark,
                areaListCurrentId: item.areaListCurrentId,
                currentId: item.currentId
              }
              //是路径
              if (item.currentId == 0) {
                faviorites_route.push(object)
              } else if (item.currentId != 0) {
                faviorites_sights.push(object)
              }
              count++
            })

            const faviorites_status = this.data.faviorites_status
            faviorites_status[this.data.currentId] = 1
            this.setData({
              faviorites_status: faviorites_status,
              faviorites: '../../images/icon/已收藏.png'
            })

            wx.setStorageSync('faviorites_route', JSON.stringify(faviorites_route))
            wx.setStorageSync('faviorites_sights', JSON.stringify(faviorites_sights))
          }
        })
      } else {
        Toast('请先登录')
      }
    } else if (this.data.faviorites_status[this.data.currentId]) {
      //已收藏
      if (app.globalData.number != 0) {
        const url = baseurl + "/route/user/delfavorites"
        const data = {
          number: app.globalData.number,
          name: this.data.pointsList[this.data.currentId].name,
          remark: this.data.pointsList[this.data.currentId].remark,
          areaListCurrentId: this.data.areaList_currentId,
          currentId: this.data.currentId
        }
        changefavorites(url, data).then(res => {
          if (res != null) {
            Toast.success('取消收藏成功')
            console.log(res);
            let faviorites_route = []
            let faviorites_sights = []
            let count = 0
            res.map(item => {
              const object = {
                id: count,
                img: areaList.areaList[item.areaListCurrentId].pointsList[item.currentId].bgi_url,
                name: item.name,
                remark: item.remark,
                areaListCurrentId: item.areaListCurrentId,
                currentId: item.currentId
              }
              //是路径
              if (item.currentId == 0) {
                faviorites_route.push(object)
              } else if (item.currentId != 0) {
                faviorites_sights.push(object)
              }
              count++
            })

            const faviorites_status = this.data.faviorites_status
            faviorites_status[this.data.currentId] = 0
            this.setData({
              faviorites_status: faviorites_status,
              faviorites: '../../images/icon/收藏.png'
            })

            wx.setStorageSync('faviorites_route', JSON.stringify(faviorites_route))
            wx.setStorageSync('faviorites_sights', JSON.stringify(faviorites_sights))
          }
        })
      } else if (app.globalData.number == 0) {
        Toast.fail('请先登录')
      }
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const that = this
    console.log(options);
    console.log(areaList);

    //地图文字参数
    if (options.currentId != null  && options.areaList_currentId != null) {
      const currentId = Number(options.currentId)
      const areaList_currentId = Number(options.areaList_currentId)
      const areaLists = areaList.areaList
      const pointsList = areaLists[areaList_currentId].pointsList
      const routeType = areaLists[areaList_currentId].routeType
      const currentpoint = brance_2[routeType][routeType]
      const markers = currentpoint.markers
      const bgi_url = []
      const VideoUrls = []
      if(currentId === 0) {
        bgi_url.push(image.image.index[routeType])
      } else if(currentId !== 0) {
        for(let i = 0;i<10;i++) {
          let bgiSting = 'http://jzroute.oss-cn-hangzhou.aliyuncs.com/'+routeType+'/'+routeType+currentId+'.'+i+'.jpg'
          bgi_url.push(bgiSting)
        }
        //找视频
        for (let i = 10; i < 13; i++) {
          let videourl = 'http://jzroute.oss-cn-hangzhou.aliyuncs.com/'+this.data.routeType+'/'+this.data.routeType+currentId+'.'+i+'.mp4'
          VideoUrls.push(videourl)
        }
      }

      console.log(pointsList);
      console.log(areaLists);

      if (!currentId) {
        that.setData({
          linear_gradient: "background: linear-gradient(to top, rgba(0, 0, 0, 0.85) 0%, rgba(0, 0, 0, 0) 70%);",
          routeName: pointsList[currentId].name,
          remark: pointsList[currentId].remark,
        })
      } else {
        this.setData({
          linear_gradient: "background: linear-gradient(to top, rgba(0, 0, 0, 0.1) 0%, rgba(0, 0, 0, 0) 70%);",
          routeName: "",
          remark: ""
        })
      }

      that.setData({
        current:currentId,
        VideoUrls:VideoUrls,
        currentId: currentId,
        routeType:routeType,
        mainColor: areaLists[areaList_currentId].color,
        pointsList: pointsList,
        bgi_url: bgi_url,
        allImageCount: bgi_url.length,
        latitude: pointsList[currentId].latitude,
        longitude: pointsList[currentId].longitude,
        scale: pointsList[currentId].scale,
        currentpoint: currentpoint,
        markers: markers,
        customCalloutMarkerIds: brance_2[routeType][routeType].customCalloutMarkerIds,
        polyline: brance_2[routeType][routeType].polyline,
        areaList: areaList.areaList,
        areaList_currentId: areaList_currentId
      })

      //加markers
      if (currentId) {
        const marker = JSON.parse(JSON.stringify(markers))
        marker.push(currentpoint.moveable_markers[currentId - 1])
        this.setData({
          markers:marker
        })
      }
    } 

    //防抖函数
    this.setData({
      swiperdebounce:debounce(function(that,currentId) {
        //设置map
      let currentpoint = JSON.parse(JSON.stringify(that.data.currentpoint));
      if (currentId != 0) {
        currentpoint.markers.push(currentpoint.moveable_markers[currentId - 1])
      }
      that.setData({
        latitude: that.data.pointsList[currentId].latitude,
        longitude: that.data.pointsList[currentId].longitude,
        scale: that.data.pointsList[currentId].scale,
  
        markers: currentpoint.markers,
        customCalloutMarkerIds: currentpoint.customCalloutMarkerIds
      })
      },300)
    })

    setTimeout(() => {
      console.log(this.data.areaList_currentId);
      //收藏
      const route = wx.getStorageSync('faviorites_route')
      const sights = wx.getStorageSync('faviorites_sights')
      if (route != "" && sights != "") {
        //有本地存储
        const faviorites_route = JSON.parse(route)
        const faviorites_sights = JSON.parse(sights)
        const faviorites_status = []
        console.log(this.data.areaList_currentId);
        faviorites_route.map(item => {
          if (item.areaListCurrentId == this.data.areaList_currentId) {
            faviorites_status[0] = 1
          }
        })
        faviorites_sights.map(item => {
          if (item.areaListCurrentId == this.data.areaList_currentId) {
            faviorites_status[item.currentId] = 1
          }
        })
        this.setData({
          faviorites_status: faviorites_status,
          faviorites: faviorites_status[0] ? '../../images/icon/已收藏.png' : '../../images/icon/收藏.png'
        })
      }
    }, 1000);

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    var mapContext = wx.createMapContext('myMap');
    this.setData({
      mapContext: mapContext
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return new Promise(resolve => {
      resolve({
        title: this.data.pointsList[this.data.currentId].name,
        imageUrl: this.data.bgi_url[0],
        path: "/pages/Pfindmore/pages/findmore/findmore?currentId=" + this.data.currentId + "&areaList_currentId=" + this.data.areaList_currentId
      })
    })
  }
})